// @ts-nocheck
import { ElNotification } from "element-plus";
// 路由鉴权,
import router from "./index.ts";
// 标题名字
let title_name = 'Vue3_Ts_模版'
// 获取仓库:因为permission实在main.js里面直接引用的，所以在先引入大仓库才能用小仓库
import pinia from "@/store/index.ts";
import useUserStore from "@/store/user.ts";
// 路由进步条：
// 引入进度条
import NProgress from "nprogress";
// 进入进度条样式
import "nprogress/nprogress.css";

// 全局前置守卫
// to:你去哪，from:你从哪来,next:路由放行跳转到哪里
router.beforeEach(async (to: any, from: any, next: any) => {
  let userStore = useUserStore(pinia);
  // 进度条开始
  NProgress.start();
  // 获取用户信息
  let username = userStore.user;
  let token = userStore.token;
  if (token) {
    if (to.path == "/login") {
      next();
    } else {
      if (username) {
        next();
      } else {
        try {
          await userStore.userInfo();
          next({ ...to });
        } catch (error) {
          // 登录失效 退出登录
          userStore.logout();
          next({ path: "/login" });
        }

      }
    }
  } else {
    if (to.path == "/login") {
      next();
    } else {
      next({
        path: "/login",
        query: { redirect: to.path },
      });
    }
  }
});

// 全局后置守卫
router.afterEach((to: any, form: any) => {
  document.title = title_name + "-" + to.meta.title;
  NProgress.done();
});
